package com.sinog.front.controller.biz;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sinog.core.model.ReplyMessage;
import com.sinog.core.model.ReportInfo;
import com.sinog.core.model.UserDTO;
import com.sinog.core.util.PageReturnUtil;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.Result;
import com.sinog.core.utilbean.ReturnCode;
import com.sinog.front.config.log.Log;
import com.sinog.front.feign.biz.ReportInfoManageService;
import com.sinog.front.service.user.UserFacade;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @desc 安帮工作资源管理 - 上报协调信息管理 - 上报协调信息管理 - ReportInfoManageController
 * @author zhangcb
 * @date 2020年2月16日 18点48分
 */
@Slf4j
@RestController
public class ReportInfoManageController {

    @Resource
    private ReportInfoManageService reportInfoManageService;
    @Autowired
    private UserFacade userService;

    /**
     * 获取首页上报协调列表
     * @return Map<String,Object>
     */
    @GetMapping("/basic/tzgg/getSySbxtList")
    public Map<String,Object> getSySbxtList() {
        UserDTO userDTO = userService.getAuthentication();
        String departId = userDTO.getDepartid();
        String account = userDTO.getAccount();
        String level = userDTO.getLevel();
        List<HashMap<String,Object>> resultList = reportInfoManageService.getSySbxtList(departId,level,account);
        List<Map<String,Object>> returnList = new ArrayList<>(16);
        Map<String,Object> resmap = new HashMap<>(16);
        for(HashMap<String,Object> stringObjectHashMap : resultList) {
            Map<String,Object> resultMap = new HashMap<>(16);
            //编号
            String id = stringObjectHashMap.get("id").toString();
            //编号
            resultMap.put("id",id);
            //标题
            resultMap.put("title",stringObjectHashMap.get("title"));
            //发布单位
            resultMap.put("fbdw",stringObjectHashMap.get("fbdw"));
            //下级用户
            resultMap.put("proid",stringObjectHashMap.get("proid"));
            //添加日期
            resultMap.put("adddate",stringObjectHashMap.get("adddate"));
            //有效期
            resultMap.put("enddate",stringObjectHashMap.get("enddate"));
            //是否标红
            resultMap.put("titlecolor","2");
            //类型
            resultMap.put("type",stringObjectHashMap.get("type"));
            int count = Integer.parseInt(stringObjectHashMap.get("new").toString());
            if(Constants.Number.NUM_ZERO != count) {
                //是否被查看
                resultMap.put("new","1");
            } else {
                //是否被查看
                resultMap.put("new","2");
            }
            try {
                ReportInfo reportInfo = reportInfoManageService.findReportById(id);
                if(ObjectUtils.isNotEmpty(reportInfo)) {
                    resultMap.put("content",reportInfo.getContent());
                } else {
                    resultMap.put("content","");
                }
            } catch(RuntimeException e) {
                log.error("发生异常:{}",e.getMessage());
            }
            returnList.add(resultMap);
        }
        resmap.put("error",Constants.Number.NUM_ZERO);
        resmap.put("data",returnList);
        resmap.put("msg","success");
        return resmap;
    }

    /**
     * 安帮工作资源管理 - 上报协调信息管理 - 上报协调信息管理 - 列表
     * @param request request
     * @param searchKey searchKey
     * @param sbStartDate sbStartDate
     * @param sbEndDate sbEndDate
     * @param sbdw sbdw
     * @param sbtype sbtype
     * @param tipFlag tipFlag
     * @return String
     */
    @GetMapping("/azbj/sbxtgl/getReportInfoList")
    public String getReportInfoList(HttpServletRequest request,
                                    @RequestParam(required = false, defaultValue = "-1") String searchKey,
                                    @RequestParam(required = false, defaultValue = "-1") String sbStartDate,
                                    @RequestParam(required = false, defaultValue = "-1") String sbEndDate,
                                    @RequestParam(required = false, defaultValue = "-1") String sbdw,
                                    @RequestParam(required = false, defaultValue = "-1") String sbtype,
                                    @RequestParam(required = false, defaultValue = "-1") String tipFlag) {
        Integer pageIndex = Integer.valueOf(request.getParameter("pageIndex"));
        Integer pageSize = Integer.valueOf(request.getParameter("pageSize"));
        String departId = userService.getAuthentication().getDepartid();
        Page<Map<String,String>> page = reportInfoManageService.getReportInfoList(searchKey,sbStartDate,sbEndDate,sbdw,sbtype,tipFlag,departId,pageIndex,pageSize);
        for(int i = 0; i < page.getRecords().size(); i++) {
            Map<String,String> resultMap = page.getRecords().get(i);
            String id = resultMap.get("id");
            try {
                ReportInfo reportInfo = reportInfoManageService.findReportById(id);
                String content = null != reportInfo ? reportInfo.getContent() : "";
                resultMap.put("content",content);
            } catch(RuntimeException e) {
                log.error("发生异常:{}",e.getMessage());
            }
            try {
                ReplyMessage replyMessage = reportInfoManageService.findMessgeById(id);
                if(ObjectUtils.isNotEmpty(replyMessage)) {
                    String content1 = replyMessage.getContent();
                    resultMap.put("content1",content1);
                }
            } catch(RuntimeException e) {
                log.error("发生异常:{}",e.getMessage());
            }
            page.getRecords().set(i,resultMap);
        }
        return PageReturnUtil.pageReturn(page);
    }

    /**
     * 安帮工作资源管理 - 上报协调信息管理 - 上报协调信息管理 - （新增/更新）
     * @param request request
     * @param data data
     * @return Result
     */
    @Log(type = "新增", value = "保存上报协调信息（新增/更新）")
    @PostMapping("/azbj/sbxtgl/reportInfoManage/save")
    public Result reportInfoManage(HttpServletRequest request,String data) {
        boolean tag = reportInfoManageService.save(data);
        if(tag) {
            return Result.success("保存成功");
        }
        return Result.failure(ReturnCode.SAVE_FAILED);
    }

    /**
     * 安帮工作资源管理 - 上报协调信息管理 - 上报协调信息管理 - 回复
     * @param data data
     * @return Result
     */
    @PostMapping("/azbj/sbxtgl/replyInfo/reply")
    public Result replyInfo(String data) {
        int tag = reportInfoManageService.reply(data);
        if(Constants.Number.NUM_ZERO != tag) {
            return Result.success("保存成功");
        }
        return Result.failure(ReturnCode.SAVE_FAILED);
    }

    /**
     * 安帮工作资源管理 - 上报协调信息管理 - 上报协调信息管理 - 获取抄送机构需要的下拉框数据
     * @return List<Map < String,Object>>
     */
    @RequestMapping("/azbj/sbxtgl/departmentInfo/getDepartmentType")
    public List<Map<String,Object>> getDepartmentType() {
        UserDTO userDTO = userService.getAuthentication();
        String departId;
        if(Constants.OrgLevel.LEVEL_JY.equals(userDTO.getLevel()) || Constants.OrgLevel.LEVEL_SFS.equals(userDTO.getLevel())) {
            departId = userDTO.getOrgid();
        } else {
            departId = userDTO.getDepartid();
        }
        return reportInfoManageService.getDepartmentType(departId);
    }

    /**
     * 安帮工作资源管理 - 上报协调信息管理 - 上报协调信息管理 - 查看时获取抄送机构需要的下拉框数据
     * @return List<Map < String,Object>>
     */
    @RequestMapping("/azbj/sbxtgl/departmentInfo/getCkDepartmentType")
    public List<Map<String,Object>> getCkDepartmentType() {
        UserDTO userDTO = userService.getAuthentication();
        String departId;
        if(Constants.OrgLevel.LEVEL_JY.equals(userDTO.getLevel()) || Constants.OrgLevel.LEVEL_SFS.equals(userDTO.getLevel())) {
            departId = userDTO.getOrgid();
        } else {
            departId = userDTO.getDepartid();
        }
        return reportInfoManageService.getDepartmentTypeInfo(departId);
    }

    /**
     * 安帮工作资源管理 - 上报协调信息管理 - 上报协调信息管理 - 发布上报协调信息
     * @param request request
     * @param id id
     * @return Result
     */
    @Log(type = "更新", value = "发布上报协调信息")
    @RequestMapping("/azbj/sbxtgl/reportInfoManage/report/{id}")
    public Result report(HttpServletRequest request,@PathVariable String id) {
        int num = reportInfoManageService.report(id);
        if(Constants.Number.NUM_ZERO < num) {
            return Result.success("上报成功");
        } else {
            return Result.failure(ReturnCode.FAILURE);
        }
    }

    /**
     * 安帮工作资源管理 - 上报协调信息管理 - 上报协调信息管理 - 取消发布上报协调信息
     * @param request request
     * @param id id
     * @return Result
     */
    @Log(type = "更新", value = "取消发布上报协调信息")
    @RequestMapping("/azbj/sbxtgl/reportInfoManage/withdraw/{id}")
    public Result withdraw(HttpServletRequest request,@PathVariable String id) {
        int num = reportInfoManageService.withdraw(id);
        if(Constants.Number.NUM_ZERO < num) {
            return Result.success("撤回成功");
        } else {
            return Result.failure(ReturnCode.FAILURE);
        }
    }

    /**
     * 安帮工作资源管理 - 上报协调信息管理 - 上报协调信息管理 - 修改查看状态
     * @param request request
     * @param id id
     * @return Result
     */
    @RequestMapping("/azbj/sbxtgl/reportInfoManage/changeState/{id}")
    public Result changeState(HttpServletRequest request,@PathVariable String id) {
        String updanwei = reportInfoManageService.getUpdanweiById(id);
        UserDTO userDTO = userService.getAuthentication();
        String departId = userDTO.getDepartid();
        //上级查看时，修改状态
        if(departId.equals(updanwei)) {
            int num = reportInfoManageService.changeState(id);
            if(Constants.Number.NUM_ZERO < num) {
                return Result.success("修改成功");
            } else {
                return Result.failure(ReturnCode.FAILURE);
            }
        }
        return Result.success("查看状态不改变");
    }
}